package com.moleq.mgpos.activities;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;

import com.moleq.base.SmartBeep;
import com.moleq.device.DeviceManager;
import com.moleq.dialog.DateSelectionDialog;
import com.moleq.dialog.MessageBox;
import com.moleq.dialog.TareDialog;
import com.moleq.enums.ItemType;
import com.moleq.logic.TransactionManager;
import com.moleq.models.BottleSetting;
import com.moleq.models.Departmant;
import com.moleq.models.ItemDiscountSetting;
import com.moleq.models.GlobalInfo;
import com.moleq.models.PosLineDiscnt;
import com.moleq.models.PosLineItem;
import com.moleq.models.PosLineTares;
import com.moleq.models.PriceSetting;
import com.moleq.models.Product;
import com.moleq.models.SaleListItem;
import com.moleq.models.SubDepartmant;
import com.moleq.models.TareSetting;
import com.moleq.mgpos.activities.R;
import com.moleq.service.ServiceManager;
import com.moleq.service.SubDepartmantService;
import com.moleq.util.BigDecmialTool;
import com.moleq.util.MoleQUtil;


public class SaleListItemCreator {

	private TransactionManager mTransMgr;
	private SaleListItem mSaleListitem;
	private Context mContext;
	private List<PosLineTares> mPosLineTaresList = new ArrayList<PosLineTares>();
	private static TareDialog mTareDialog;
	
	public SaleListItemCreator(Context context) {
		mContext = context;
		mTransMgr = TransactionManager.getInstance();
	}



	

//	private String weight_unit;
	private Product product;
	public double tare = 0;
	private BottleSetting mBottleSetting;
//	private Departmant deptSetting;
	private SubDepartmant deptSetting;
	private SubDepartmantService mSubDepartmantService;
	private boolean mLoadPendingItemMode = false;
	private static DateSelectionDialog mDateSelectionDialog;
	private List<TareSetting> mTareSetting = new ArrayList<TareSetting>();
	public void buildItemByUpc(String inputText,int currentQty) {
		
		String upc = inputText;
		mSaleListitem = mTransMgr.mSaleListItems.createItem();
		mSaleListitem.setUpc(upc);
		
//		doPackageItem();
		
		tare = 0;

		if (mSaleListitem.getPkgItem()) 
//			upc = mSaleListitem.getPkgitemno();
		
		product = ServiceManager.getInstance().mProductService.Find(upc);

		if (product != null && product.getIsActive().equals("A")) {

			if (!mSaleListitem.getPkgItem()) {
				mSaleListitem.setUpc(product.getBarcode());
				mSaleListitem.setUnitPrice(product.getPrice());
				mSaleListitem.setQty(currentQty);
			}

			mSaleListitem.setName(product.getName1());
			mSaleListitem.setDescription(product.getDesc());
			
			mSaleListitem.setDisplayContent(product.getName1());
			mSaleListitem.setBottleDeposit(product.getBottle_deposit());
			
			if (mSaleListitem.getBottleDeposit() > 0) {
				mBottleSetting = ServiceManager.getInstance().mBottleSettingService.Find(mSaleListitem.getBottleDeposit());
				if (mBottleSetting != null) {
					mSaleListitem.setmBottleSeting(mBottleSetting);
				}
			}

			mSaleListitem.setTareCount(ServiceManager.getInstance().mTareSettingService.HaveTare(product.getBarcode()));
			mSaleListitem.setDep(product.getDep());
			mSaleListitem.setFollowdep(product.getFollowdep());

			// set tax1 , tax2 ,tax3 ,tax4
			double dep = product.getDep();
			if (dep > 0) {
				deptSetting = ServiceManager.getInstance().mSubDepartmantService.Find(dep);
				mSaleListitem.setDep_group(ServiceManager.getInstance().mDepartmantService.Find(deptSetting.getF03()).getGroup_no());
			}
			if (product.getFollowdep() == true) {
				if (deptSetting != null) {
					mSaleListitem.setTax1(deptSetting.getTax1());
					mSaleListitem.setTax2(deptSetting.getTax2());
					mSaleListitem.setTax3(deptSetting.getTax3());
					mSaleListitem.setTax4(deptSetting.getTax4());
					mSaleListitem.setTax5(deptSetting.getTax5());
					mSaleListitem.setTax6(deptSetting.getTax6());
					mSaleListitem.setIsWeight(deptSetting.getScale_weight());
					mSaleListitem.setFoodstamp(deptSetting.getFood_stamp());
					mSaleListitem.setAge(ServiceManager.getInstance().mAgeSettingService.FindAge(deptSetting.getAge()));
					mSaleListitem.setNodiscount(deptSetting.getNo_discnt());
				}
			} else {
				mSaleListitem.setTax1(product.getTax1());
				mSaleListitem.setTax2(product.getTax2());
				mSaleListitem.setTax3(product.getTax3());
				mSaleListitem.setTax4(product.getTax4());
				mSaleListitem.setTax5(product.getTax5());
				mSaleListitem.setTax6(product.getTax6());
				mSaleListitem.setIsWeight(product.isWeight());
				mSaleListitem.setFoodstamp(product.getFoodstamp());
				mSaleListitem.setAge(ServiceManager.getInstance().mAgeSettingService.FindAge(product.getAgeLinkNo()));
				mSaleListitem.setNodiscount(product.getNodiscount());
			}

			if (mTransMgr.Age > 0) {
				if (mSaleListitem.getAge() > mTransMgr.Age) {
					if (this.mLoadPendingItemMode ) {
						// if(!mMessageDlgIsShowing){
						MessageBox.show(mContext, mContext.getResources().getString(R.string.msg_not_old_enough_2));
						// }
					} else {
						// if(!mMessageDlgIsShowing){
						MessageBox.show(mContext, mContext.getResources().getString(R.string.msg_not_old_enough_1));
						// }
					}
					return;
				}
			} else {
				if (mSaleListitem.getAge() > 0) {
					if (mDateSelectionDialog == null) {
						mDateSelectionDialog = new DateSelectionDialog(mContext);
					}
				
					if (mDateSelectionDialog == null || mDateSelectionDialog.isShowing()) 
					mDateSelectionDialog.show();
					return;
				}
			}
			ProcessedAge();
		} else {
			if (mPosLineItem != null && mPosLineItem.getUpc().substring(0, 1).equals("D") && mLoadPendingItemMode) {
				int depno = Integer.valueOf(mPosLineItem.getUpc().substring(1));
				deptSetting = ServiceManager.getInstance().mSubDepartmantService.Find(depno);
				mSaleListitem.setPrice(mPosLineItem.getPrice());
				mSaleListitem.setName(deptSetting.getSd_name());
				mSaleListitem.setDisplayContent(deptSetting.getSd_name());
				mSaleListitem.setWeightDesc("");
				mSaleListitem.setmTareDesc("");
				mSaleListitem.setQty(mPosLineItem.getQty());
				mSaleListitem.setUpc(mPosLineItem.getUpc());
				mSaleListitem.setTax1(deptSetting.getTax1());
				mSaleListitem.setTax2(deptSetting.getTax2());
				mSaleListitem.setTax3(deptSetting.getTax3());
				mSaleListitem.setTax4(deptSetting.getTax4());
				mSaleListitem.setTax5(deptSetting.getTax5());
				mSaleListitem.setTax6(deptSetting.getTax6());
				mSaleListitem.setFoodstamp(deptSetting.getFood_stamp());
				mSaleListitem.setItemType(ItemType.OPEN_DEPARTMENT);
				mSaleListitem.setNodiscount(deptSetting.getNo_discnt());

				mTransMgr.mSaleListItems.addItemToList(mSaleListitem);
//				mTransMgr.mSaleListItems.showCurrentSaleItem(mSaleListitem);
//				showItemToDisplayScreen(mSaleListitem);
			} else {
				SmartBeep.getInstance().play(SmartBeep.SOUND_ERROR);

				MessageBox.show(mContext, mContext.getResources().getString(R.string.msg_item_not_found));
			}

			TransactionManager.getInstance().announceChanges();
		}
	
		
	}

	private PosLineItem mPosLineItem;
	
	
//	public void doPackageItem() {
//		
//		int pricedigits = 4;
//		if(GlobalInfo.getInstance().priceDigits > 0)
//			pricedigits = GlobalInfo.getInstance().priceDigits;
//		
//		int iLength, iZeros;
//		String upc = mSaleListitem.getUpc();
//		String ls_left = upc.substring(0, 2);
//		iLength = upc.length();
//
//		if (ls_left.equals("02") && iLength == 12) {
//
//			int priceindex = (pricedigits == 4) ? 8 : 7;
//			double pkgprice = Double.valueOf(upc.substring(priceindex, 12)) * 0.01;
//			// mSaleListitem.
//			upc = upc.substring(0, 7) + "00000";
//
//			mSaleListitem.setPkgitemno(upc);
//			mSaleListitem.setUnitPrice(pkgprice);
//			mSaleListitem.setPkgItem(true);
//			mSaleListitem.setQty(1);
//		}
//	}
	
	public void ProcessedAge() {


		if (this.mTransMgr.Age > 0 && mSaleListitem.getAge() > this.mTransMgr.Age) {
			MessageBox.show(mContext, mContext.getResources().getString(R.string.msg_not_old_enough_1));
			mTransMgr.announceChanges();
			return;
		}

		// set pos line tare
		mPosLineTaresList = new ArrayList<PosLineTares>();
		if (mPosLineItem != null && mLoadPendingItemMode == true) {
			mSaleListitem.setPoslineno(mPosLineItem.getNo());
			mSaleListitem.setQty(mPosLineItem.getQty());
			mPosLineTaresList = ServiceManager.getInstance().mPosLineTaresService.Find(mPosLineItem.getNo());
			// ========= wei ============
			if (mPosLineTaresList != null && mPosLineTaresList.size() > 1) {
				for (int i = 0; i < mPosLineTaresList.size(); i++) {
					TareSetting tsetting = new TareSetting();
					tsetting.setQty(mPosLineTaresList.get(i).getLt_qty());
					tsetting.setTa_no(mPosLineTaresList.get(i).getLt_tare_no());
					mTareSetting.add(tsetting);
				}
				mSaleListitem.setmTareSetting(mTareSetting);
				mSaleListitem.setTareCount(mPosLineTaresList.size());
			}
			// =========================
		}

		if (mSaleListitem.getPkgItem()) {
			mSaleListitem.setIsWeight(false);
		}

		if (mPosLineTaresList != null && mPosLineTaresList.size() > 0) {
			mSaleListitem.setHavepolinetare(true);
			mSaleListitem.setmTareSetting(mTareSetting);
			// mSaleListitem.setmTareDesc(" Tare " +
			// MoleQUtil.fixWeight(poslinetare,getUnit())
			// + weight_unit);
		} else {
			mSaleListitem.setHavepolinetare(false);
		}

		if (mSaleListitem.getTareCount() > 0 && mSaleListitem.getIsWeight() && mSaleListitem.getHavepolinetare() == false) {

			if (mSaleListitem.getTareCount() > 1) {
				if (mTareDialog == null) {
					mTareDialog = new TareDialog(mContext, mSaleListitem);
					mTareDialog.show();
				} else {
					if (mTareDialog.isShowing()) {
						mTareDialog.dismiss();
					}
					mTareDialog = new TareDialog(mContext, mSaleListitem);
					mTareDialog.show();
				}
				return;
			}
			mTareSetting = ServiceManager.getInstance().mTareSettingService.Find(mSaleListitem.getUpc());
			mSaleListitem.setmTareSetting(mTareSetting);
			tare = BigDecmialTool.round(mTareSetting.get(0).getTa_value() * GlobalInfo.getInstance().tareRate, getUnit());

		}
		additemdetail();

	}
	
	public int getUnit() {
		int checkunit = 2;
		String unit =GlobalInfo.getInstance().weightUnit;
		if (unit.equals("oz")) {
			checkunit = 1;
		} else if (unit.equals("lb")) {
			checkunit = 2;
		} else if (unit.equals("kg")) {
			checkunit = 3;
		}
		return checkunit;
	}
	
	public boolean additemdetail() {
		if (mSaleListitem.getIsWeight()) {

			if (mLoadPendingItemMode) {
				mSaleListitem.setWeight(mPosLineItem.getWeight());
				mSaleListitem.setPrice(mPosLineItem.getPrice());
				mSaleListitem.setWeightDesc(MoleQUtil.fixWeight(mSaleListitem.getWeight(), getUnit()) + GlobalInfo.getInstance().weightUnit);

				if (mSaleListitem.getHavepolinetare()) {
					double poslinetare = ServiceManager.getInstance().mPosLineTaresService.getTotalTare(mPosLineItem.getNo()) * GlobalInfo.getInstance().tareRate;

					if (poslinetare > 0) {
						mSaleListitem.setWeightDesc(MoleQUtil.fixWeight(mSaleListitem.getWeight(), getUnit()) + GlobalInfo.getInstance().weightUnit);
						mSaleListitem.setmTareDesc(" Tare " + MoleQUtil.fixWeight(poslinetare, getUnit()));
					} else {
						poslinetare = ServiceManager.getInstance().mPosLineTaresService.getManualTare(mPosLineItem.getNo()) * GlobalInfo.getInstance().tareRate;
						mSaleListitem.setWeightDesc(MoleQUtil.fixWeight(mSaleListitem.getWeight(), getUnit()) + GlobalInfo.getInstance().weightUnit);
						mSaleListitem.setmTareDesc(" Tare " + MoleQUtil.fixWeight(poslinetare, getUnit()));
					}
				}
			} else {
				mSaleListitem.setQty(1);
				double receiveWeight = 0;
				if (DeviceManager.getInstance().scaleIsReady) {

					receiveWeight = DeviceManager.getInstance().scale.getWeight();
					receiveWeight = BigDecmialTool.round(receiveWeight, getUnit());// /
																					// 100;
					if (receiveWeight == 0) {
						MessageBox.show(mContext, mContext.getResources().getString(R.string.msg_no_weight));

						return false;
					}
				} else {
					return false;
				}
				String weigthdesc = MoleQUtil.fixWeight(receiveWeight, getUnit()) + GlobalInfo.getInstance().weightUnit;
				if (tare > 0) {
					if (tare > receiveWeight) {
						return false;
					}
					receiveWeight = receiveWeight - tare;
					weigthdesc = MoleQUtil.fixWeight(receiveWeight, getUnit()) + GlobalInfo.getInstance().weightUnit;
					mSaleListitem.setmTareDesc(" Tare " + MoleQUtil.fixWeight(tare, getUnit()));
				}
				mSaleListitem.setWeight(receiveWeight);
				mSaleListitem.setPrice(mSaleListitem.getUnitPrice() * receiveWeight);
				mSaleListitem.setWeightDesc(weigthdesc);

			}
		} else {
			setManualTare(0);
			mSaleListitem.setWeight(0);
			mSaleListitem.setPrice(mSaleListitem.getUnitPrice() * mSaleListitem.getQty());
		}

		PriceSetting setting = ServiceManager.getInstance().mPriceService.getitemprice(product.getBarcode());
		if (mSaleListitem.getPkgItem()) {

		} else {
			if (setting != null) {
				if (setting.haveMixAndMatch && !mSaleListitem.getIsWeight()) {
					String mmNum = setting.getPricemm();
					setting = ServiceManager.getInstance().mMixMatchService.findSettingByUpc(mSaleListitem.getUpc());
					setting.setPricemm(mmNum);
					setting.isMixAndMatch = true;
					mSaleListitem.setMixMatch(mmNum);
					mSaleListitem.setMixMatchDesc(" MM ");
				}
			}

			mSaleListitem.setPriceSetting(setting);
		}

		//
		if (mTransMgr.manualTare > 0) {
			if (tare <= 0) {
				double tare = mTransMgr.manualTare * GlobalInfo.getInstance().tareRate;//mPosSetting.getPs_tare_rate();
				mSaleListitem.setWeight(mSaleListitem.getWeight() - tare);
				mSaleListitem.setWeightDesc(MoleQUtil.fixWeight(mSaleListitem.getWeight(), getUnit()) + GlobalInfo.getInstance().weightUnit);
				mSaleListitem.setmTareDesc(" Tare " + MoleQUtil.fixWeight(tare, getUnit()));
				TareSetting tsetting = new TareSetting();
				tsetting.setTa_no(0);
				tsetting.setQty(mTransMgr.manualTare);
				mSaleListitem.setTareCount(1);
				mTareSetting.add(tsetting);
				mSaleListitem.setmTareSetting(mTareSetting);
				GlobalInfo.getInstance().useFuntionsList.add(GlobalInfo.getInstance().CurrentFreeFuncID);
				mTransMgr.SaveFreeFuncRpt(GlobalInfo.getInstance().CurrentFreeFuncID, 1, 0);
			}
			setManualTare(0);
		}

		mTransMgr.mSaleListItems.addItem(mSaleListitem);
//		mTransMgr.mSaleListItems.showCurrentSaleItem(mSaleListitem);

//		Bitmap bm = ServiceManager.getInstance().mPicService.getImageByUPC(mSaleListitem.getUpc());
//		showImage(bm);
//		showItemToDisplayScreen(mSaleListitem);

		if (mLoadPendingItemMode) {
			List<PosLineDiscnt> mPosLineDiscnt = ServiceManager.getInstance().mPosLineDiscntService.Find(mSaleListitem.getPoslineno());
			if (mPosLineDiscnt != null && mPosLineDiscnt.size() > 0) {

				ItemDiscountSetting mDiscountSetting = null;
				double dnt = 0;
				int discntno = 0;
				String desc = "";
				for (int i = 0; i < mPosLineDiscnt.size(); i++) {

					mDiscountSetting = ServiceManager.getInstance().mDiscountSettingService.Find(mPosLineDiscnt.get(i).getLd_discnt_no());
					if (mDiscountSetting != null) {
						dnt = mDiscountSetting.getDs_value();
						discntno = mDiscountSetting.getDs_no();
						desc = mDiscountSetting.getDs_desc();
					}
					SaleListItem discntAmtItem = mTransMgr.mSaleListItems.createItem();
					discntAmtItem.setParentId(mSaleListitem.getId());
					discntAmtItem.setPoslineno(mSaleListitem.getPoslineno());
					discntAmtItem.setTax1(mSaleListitem.getTax1());
					discntAmtItem.setTax2(mSaleListitem.getTax2());
					discntAmtItem.setTax3(mSaleListitem.getTax3());
					discntAmtItem.setTax4(mSaleListitem.getTax4());
					discntAmtItem.setTax5(mSaleListitem.getTax5());
					discntAmtItem.setTax6(mSaleListitem.getTax6());
					discntAmtItem.setFoodstamp(mSaleListitem.getFoodstamp());
					discntAmtItem.setNodiscount(mSaleListitem.getNodiscount());
					discntAmtItem.setPoslinediscntno(discntno);

					discntAmtItem.setItemType(ItemType.ITEM_DISCOUNT_PERECENT);
					discntAmtItem.setUpc("ITEM_DISCOUNT_PERCENT");

					dnt = BigDecmialTool.div(dnt, 100);
					dnt = BigDecmialTool.mul(mSaleListitem.getPrice(), dnt);
					dnt = BigDecmialTool.mul(-1, dnt);
					discntAmtItem.setPrice(dnt);
					discntAmtItem.setName(desc);
					discntAmtItem.setDisplayContent(desc);
					discntAmtItem.setQty(1);
					discntAmtItem.setHavepolinediscnt(true);

					mTransMgr.mSaleListItems.addItemToList(discntAmtItem);
//					mTransMgr.mSaleListItems.showCurrentSaleItem(discntAmtItem);
//					showItemToDisplayScreen(discntAmtItem);
				}
			}
		}
		// ShowAge();

		TransactionManager.getInstance().announceChanges();
		return true;

	}
	
	public void setManualTare(double tare) {
		if (tare > 0) {
//			tv_tare.setVisibility(View.VISIBLE);
//			tv_tare_num.setVisibility(View.VISIBLE);
//			tv_tare_num.setText(MoleQUtil.fixNumber(tare));
		} else {
//			tv_tare.setVisibility(View.INVISIBLE);
//			tv_tare_num.setVisibility(View.INVISIBLE);
//			tv_tare_num.setText(MoleQUtil.fixNumber(0));
			mTransMgr.manualTare = 0;
		}
	}

}
